package testCase

import (
	"autoTestNew/pkg/commonType"
	"context"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	ctrl "sigs.k8s.io/controller-runtime"
)

var log = ctrl.Log.WithName("mongodb/testCase")

type Store struct {
	collection *mongo.Collection
}

func NewStore(db *mongo.Database) *Store {
	return &Store{
		collection: db.Collection("testCase"),
	}
}

// Create 测试用例
func (s *Store) Create(ctx context.Context, testCase commonType.TestCase) (commonType.TestCase, error) {
	if testCase.ID == nil {
		newID := primitive.NewObjectID()
		testCase.ID = &newID
	}
	result, err := s.collection.InsertOne(ctx, testCase)
	if err != nil {
		log.Error(err, "create testCase failed", "testCase", testCase)
		return commonType.TestCase{}, err
	}
	objectID := result.InsertedID.(primitive.ObjectID)
	testCase.ID = &objectID
	return testCase, nil
}

// Get 获取测试用例
func (s *Store) Get(ctx context.Context, id primitive.ObjectID) (commonType.TestCase, error) {
	var testCase commonType.TestCase
	err := s.collection.FindOne(ctx, primitive.M{"_id": id}).Decode(&testCase)
	if err != nil {
		log.Error(err, "get testCase error", "id", id)
		return commonType.TestCase{}, err
	}
	return testCase, nil
}

// GetListByTestMicroserviceId  根据testMicroservice_id获取测试用例列表
func (s *Store) GetListByTestMicroserviceId(ctx context.Context, testMicroserviceId primitive.ObjectID) ([]commonType.TestCase, error) {
	var testCase []commonType.TestCase
	cursor, err := s.collection.Find(ctx, primitive.M{"testMicroservice_id": testMicroserviceId})
	if err != nil {
		log.Error(err, "get testCase list error", "testMicroservice_id", testMicroserviceId)
		return nil, err
	}
	err = cursor.All(ctx, &testCase)
	if err != nil {
		log.Error(err, "get testCase list error", "testMicroservice_id", testMicroserviceId)
		return nil, err
	}
	return testCase, nil
}

func (s *Store) Update(ctx context.Context, id primitive.ObjectID, testCase commonType.TestCase) interface{} {
	_, err := s.collection.UpdateOne(ctx, primitive.M{"_id": id}, primitive.M{"$set": testCase})
	if err != nil {
		log.Error(err, "update testCase error", "id", id)
		return err
	}
	return nil
}
